package it.traveldream.EJB;

import it.traveldream.EJB.DTO.CittaDTO;
import it.traveldream.EJB.DTO.StatoDTO;
import it.traveldream.EJB.entities.Citta;
import it.traveldream.EJB.entities.Stati;
import it.traveldream.utility.Entities2DTO;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class CityCountryBeanImpl
 */
@Stateless
public class CityCountryBeanImpl implements CityCountryBean {

	@PersistenceContext
	EntityManager em;
	
    /**
     * Default constructor. 
     */
    public CityCountryBeanImpl() {
        // TODO Auto-generated constructor stub
    }
    
    public CityCountryBeanImpl(EntityManager emg){
		if(em==null){
			em=emg;
		}
	}
    
    /**
     * Ritorna le {@link Citta} presenti nel database.
     * 
     * @return i dati in un'{@link ArrayList} di {@link CittaDTO}
     * 
     */
    @Override
    public ArrayList<CittaDTO> getAllCitta(){
    	ArrayList<CittaDTO> result = new ArrayList<CittaDTO>();
    	List<Citta> lc;
    	
    	lc = em.createQuery("SELECT c FROM Citta c").getResultList();
    	
    	Iterator<Citta> i = lc.iterator();
    	
    	while(i.hasNext()){
    		result.add(Entities2DTO.convertCitta(i.next()));
    	}
    	
    	return result;
    }
    
    /**
     * Ritorna le {@link Citta} presenti nel database che iniziano con il path passato.
     * 
     * @param start = Stringa contenente l'inizio delle citt� da cercare nel database
     * 
     * @return i dati in un'{@link ArrayList} di {@link CittaDTO}
     * 
     */
    @Override
    public ArrayList<CittaDTO> getFilteredCitta(String start){
    	ArrayList<CittaDTO> result = new ArrayList<CittaDTO>();
    	List<Citta> lc;
    	
    	lc = em.createQuery("SELECT c FROM Citta c WHERE c.name LIKE '"+start+"%'").getResultList();
    	
    	Iterator<Citta> i = lc.iterator();
    	
    	while(i.hasNext()){
    		result.add(Entities2DTO.convertCitta(i.next()));
    	}
    	
    	return result;
    }
    
    /**
     * Ritorna le {@link Stati} presenti nel database.
     * 
     * @return i dati in un'{@link ArrayList} di {@link StatiDTO}
     * 
     */
    @Override
    public ArrayList<StatoDTO> getAllStati(){
    	ArrayList<StatoDTO> result = new ArrayList<StatoDTO>();
    	List<Stati> lc;
    	
    	lc = em.createQuery("SELECT c FROM Stati c").getResultList();
    	
    	Iterator<Stati> i = lc.iterator();
    	
    	while(i.hasNext()){
    		result.add(Entities2DTO.convertStati(i.next()));
    	}
    	
    	return result;
    }

}
